package com.zy.chat.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zy.chat.entity.MsgSession;
import com.zy.chat.mapper.MsgSessionMapper;
import com.zy.chat.service.MsgSessionService;
import com.zy.chat.util.TimeUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Map;
import java.util.stream.Collectors;


@Service
public class MsgSessionServiceImpl extends ServiceImpl<MsgSessionMapper, MsgSession> implements MsgSessionService {



    @Autowired
    private MsgSessionMapper msgSessionMapper;
    @Override
    public Map<String,Integer> queryAll(String username) {
        ArrayList<MsgSession> list = new ArrayList<>();
        QueryWrapper<MsgSession> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("to_user",username);
       return msgSessionMapper.selectList(queryWrapper).stream().collect(Collectors.toMap(MsgSession::getFromUser,MsgSession::getNoread));
    }

    @Override
    public Integer update(String username, String touser, Integer noreadnum) {
        UpdateWrapper<MsgSession> updateWrapper = new UpdateWrapper<>();
        updateWrapper.eq("from_user",username).eq("to_user",touser).set("noread",noreadnum);
        return  msgSessionMapper.update(null,updateWrapper);
    }

    @Override
    public Integer offlineInsert(String username, String touser) {
        QueryWrapper<MsgSession> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("from_user",username).eq("to_user",touser);
        MsgSession msgSession = msgSessionMapper.selectOne(queryWrapper);
        if (msgSession == null) {
            // 会话表不存在，创建新的会话并插入数据库
            MsgSession newSession = new MsgSession();
            newSession.setFromUser(username);
            newSession.setToUser(touser);
            newSession.setUpdateTime(LocalDateTime.now().toString()); // 设置更新时间
            newSession.setNoread(0); // 初始化未读消息数为0

            msgSessionMapper.insert(newSession); // 插入会话表

            return 1; // 返回未读消息数为0
        } else {
            // 会话表已存在，将未读消息数加1并更新数据库
            msgSession.setNoread(msgSession.getNoread() + 1);
            msgSession.setUpdateTime(LocalDateTime.now().toString()); // 更新更新时间

            msgSessionMapper.update(msgSession,null); // 更新会话表

            return msgSession.getNoread(); // 返回更新后的未读消息数
        }

    }


}
